<?php

namespace App\Mobile\Controllers;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use DB;
use Auth;
use Validator;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\PacketLog;
use App\User;
use App\EveryDayTicketLog;
use App\WxPublicUser;

class PacketController extends Controller
{
	protected $config = [
    	'app_id' => 'wxb19dc538de82d329',
	    'secret' => 'a14a0d4744840960f16866056f7da387',
	    // payment
	    'payment' => [
	        'merchant_id' => '1502450861',
	        'key' => 'leyouleyouleyouleyouleyouleyou18',
	    	'cert_path' => '/home/app_cert/apiclient_cert.pem',
	    	'key_path' => '/home/app_cert/apiclient_key.pem',
	    ],
	    'log' => [
	    ],
	];

	/**
	 * [sendPacket 发送红包]
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function sendPacket(Request $request)
	{
		if (!$request->input('openid')) {
			return ['flag' => false, 'msg' => 'openid不能为空'];
		}
		if (!$request->input('userid')) {
			return ['flag' => false, 'msg' => 'userid不能为空'];
		}
		if (!$request->input('money')) {
			return ['flag' => false, 'msg' => 'money不能为空'];
		}
		if (!$request->input('message')) {
			return ['flag' => false, 'msg' => 'message不能为空'];
		}
		if (!$request->input('signature')) {
			return ['flag' => false, 'msg' => '签名不能为空'];
		}
		$valide = sha1("userid=".$request->input('userid')."&openid=".$request->input('openid')."&key=LEYOUGAME2018[]");
		if ($valide != $request->input('signature')) {
			return ['flag' => false, 'msg' => '签名错误'];
		}
		if ($request->input('money') < 1) {
			return ['flag' => false, 'msg' => '金额错误'];
		}
    	$app = new Application($this->config);
		$merchantPay = $app->merchant_pay;
        $merchantPayData = [
            'partner_trade_no' => str_random(16), //随机字符串作为订单号，跟红包和支付一个概念。
            'openid' => $request->input('openid'), //收款人的openid
            'check_name' => 'NO_CHECK',  //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
            're_user_name'=>'张三',     //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
            'amount' => $request->input('money') * 100,  //单位为分
            'desc' => '企业付款',
            'spbill_create_ip' => '47.95.202.91',  //发起交易的IP地址
        ];
        $result = $merchantPay->send($merchantPayData);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
        	$log = new PacketLog;
        	$log->userid = $request->input('userid');
        	$log->money = $request->input('money');
        	$log->message = $request->input('message');
        	$log->status = 1;
        	$log->save();
        	$user = User::where(['userid' => $request->input('userid')])->first();
        	if ($user) {
	        	$wx_user = WxPublicUser::where(['unionid' => substr($user->account, 3)])->first();
	        	if ($wx_user) {
	        		$obj = new HomeController;
	        		$obj->sendMsg($wx_user, ['message' => $request->input('message'), 'money' => $request->input('money')]);  
	        	}
        	}
        	
	        return ['flag' => true];
        } else {
        	$log = new PacketLog;
        	$log->userid = $request->input('userid');
        	$log->money = $request->input('money');
        	$log->message = $request->input('message');
        	$log->err_message = $result->err_code_des;
        	$log->save();
        	return ['flag' => false, 'msg' => $result->err_code_des];
        } 
	}

	/**
	 * [index 领取每日银票]
	 * @param  User   $user [description]
	 * @return [type]       [description]
	 */
	public function index(User $user)
	{
		$is_take = false;
		$begin_time = strtotime(date('Y-m-d',time()));
		$end_time = strtotime(date('Y-m-d',strtotime('+1 day')));
		$log = EveryDayTicketLog::where(['userid' => $user->userid])->where('judge_time', '>', $begin_time)->where('judge_time', '<=', $end_time)->first();
		if ($log) {
			$is_take = true;
		}
		return view('mobile.ticket.index', compact('is_take', 'user'));
	}

	/**
	 * [take 领取银票]
	 * @return [type] [description]
	 */
	public function take(User $user, Request $request)
	{
		$begin_time = strtotime(date('Y-m-d',time()));
		$end_time = strtotime(date('Y-m-d',strtotime('+1 day')));
		$log = EveryDayTicketLog::where(['userid' => $user->userid])->where('judge_time', '>', $begin_time)->where('judge_time', '<=', $end_time)->first();
		if (!$log) {
			$user->gems += 1;
			$log = new EveryDayTicketLog;
			$log->userid = $user->userid;
			$log->count = $request->input('count');
			$log->judge_time = time();
			DB::beginTransaction();
	    	try {
	    		$user->save();
	    		$log->save();
	        	DB::commit();

	        	return ['flag' => true, 'msg' => '领取成功'];
	    	} catch (Exception $e) {
	    		DB::rollback();
	    		return ['flag' => true, 'msg' => '事务执行失败，数据回滚'];
	    	}
		}
	}

}	